package com.lzq.mq.nameserver.event.spi.listener;

import com.lzq.mq.common.coder.TcpMsg;
import com.lzq.mq.common.constants.NameServerConstants;
import com.lzq.mq.common.enums.NameServerResponseCode;
import com.lzq.mq.common.event.Listener;
import com.lzq.mq.nameserver.common.CommonCache;
import com.lzq.mq.nameserver.event.model.UnRegistryEvent;
import io.netty.channel.ChannelHandlerContext;
import io.netty.util.Attribute;
import io.netty.util.AttributeKey;
import io.netty.util.internal.StringUtil;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class UnRegisterListener implements Listener<UnRegistryEvent> {
    @Override
    public void onReceive(UnRegistryEvent event) {

        log.info("收到注销请求:{}", event);
        ChannelHandlerContext channelHandlerContext = event.getChannelHandlerContext();
        Attribute<String> reqId = channelHandlerContext.channel().attr(AttributeKey.valueOf(NameServerConstants.NAMESERVER_CHANNEL_ID));
        String address = reqId.get();
        if (StringUtil.isNullOrEmpty(address)) {
            log.error("下线参数异常:{}", event);
        }
        String[] split = address.split(":");
        String ip = split[0];
        Integer port = Integer.parseInt(split[1]);

        // 移除记录
        CommonCache.getServiceInstanceManager().remove(ip, port);

        // 响应请求
        TcpMsg tcpMsg = new TcpMsg(
                NameServerResponseCode.UN_REGISTRY_SERVICE.getCode(),
                NameServerResponseCode.UN_REGISTRY_SERVICE.getDesc().getBytes()
        );

        channelHandlerContext.writeAndFlush(tcpMsg);
        // 关闭通道
        channelHandlerContext.close();
    }
}
